const express = require('express')
const router = express.Router()
const ModsPack = require('../db/index').ModsPack
const UUIDUtils = require('../utils/UUIDUtils')
const FileUtils = require('../utils/FileUtils')
const ResultPo = require('../po/ResultPo')
const moment = require('moment')
const fs = require('fs-extra')
const path = require('path')

// 新增或修改
router.post('/', (req, res, next) => {
	if (!req.body) return res.send(new ResultPo('参数不能为空'))
	if (!req.body.dir) return res.send(new ResultPo('MOD文件不能为空'))
	const id = req.body.id
	const dir = req.body.dir
	const params = req.body
	delete params.id
	if (id) {
		ModsPack.edit(params, [{
				key: 'id',
				value: id
			}],
			(err, result) => {
				if (err) return next(err)
				res.send('OK')
			})
	} else {
		// 设置UUID
		const ID = UUIDUtils.getUUID()
		// 创建文件夹路径
		FileUtils.createDir(global.homeDir, 'mods', ID)
		// 冲突的文件复制替换，不冲突的文件不变
		fs.copySync(dir, path.join(global.homeDir, 'mods', ID))
		params.id = ID
		// 设置默认值
		params.status = 3
		params.create_date = moment().format('YYYY-MM-DD HH:mm:ss')
		ModsPack.create(params,
			(err, result) => {
				if (err) return next(err)
				res.send('OK')
			})
	}
})
// 根据id查询
router.get('/:id', (req, res, next) => {
	const id = req.params.id
	ModsPack.find(id, (err, result) => {
		if (err) return next(err)
		res.send(result)
	})
})
// 分页查询
router.get('/', (req, res, next) => {
	const params = {
		title: req.query.title
	}
	const page = {
		limit: req.query.limit,
		offset: req.query.offset
	}
	ModsPack.page(params, page, (err, arr) => {
		if (err) return next(err)
		res.send(arr)
	})
})
// 删除
router.delete('/:id', (req, res, next) => {
	const id = req.params.id
	ModsPack.delete(id, (err) => {
		if (err) return next(err)
		res.send(new ResultPo('删除成功'))
	})
})
router.post('/test', (req, res, next) => {
	const url = 'E:\\tsest\\'
	const des = 'E:\\cpy'
	res.send(new ResultPo('成功'))
})

module.exports = router;
